package org.mybatis.generator.codegen.mybatis3.controller.elements;

import java.util.Set;
import java.util.TreeSet;

import org.mybatis.generator.api.dom.java.FullyQualifiedJavaType;
import org.mybatis.generator.api.dom.java.JavaVisibility;
import org.mybatis.generator.api.dom.java.Method;
import org.mybatis.generator.api.dom.java.Parameter;
import org.mybatis.generator.api.dom.java.TopLevelClass;

/**
 * controller 添加方法
 *
 * @author tangdelong
 * 2015年5月25日
 */
public class AddMethodControllerGenerator extends AbstractJavaControllerMethodGenerator {

	@Override
	public void addControllerElements(TopLevelClass topLevelClass) {
		FullyQualifiedJavaType model = new FullyQualifiedJavaType(introspectedTable.getBaseRecordType());
		
		Set<FullyQualifiedJavaType> importedTypes = new TreeSet<FullyQualifiedJavaType>();
		Method method = new Method();
		method.setVisibility(JavaVisibility.PUBLIC);
		method.setReturnType(new FullyQualifiedJavaType("java.lang.String"));
		method.setName(model.getInjectName()+"Add");

		method.addAnnotation("@RequestMapping(\"/"+model.getInjectName()+"Add\")");
		
		
		FullyQualifiedJavaType param = new FullyQualifiedJavaType(introspectedTable.getBaseRecordType());
		method.addParameter(new Parameter(param, "param"));
		
		
		// 方法内容
		FullyQualifiedJavaType service = new FullyQualifiedJavaType(introspectedTable.getMyBatis3JavaServiceType());
		method.addBodyLine(service.getInjectName() + "." + introspectedTable.getInsertSelectiveStatementId() + "(param);");
		method.addBodyLine("return \"redirect:/"+model.getInjectName()+"/"+model.getInjectName()+"Search\";");

		context.getCommentGenerator().addGeneralMethodComment(method, introspectedTable, "添加记录");

		if (context.getPlugins().clientDeleteByPrimaryKeyMethodGenerated(method, topLevelClass, introspectedTable)) {
			topLevelClass.addImportedTypes(importedTypes);
			topLevelClass.addMethod(method);
		}


	}

}
